import { asyncRoutes, constantRoutes } from "@/router";
import { getPermissionMenu } from "@/api/system";

var btnAuthorityList = [];

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta) {
    if (route.meta.code) {
      
      let result = roles.some(role => route.meta.code === role.code);
      if (result) {
        route.meta.permission = 1
      }
      return result
    } else {
      return true
    }
  } else {
    return true;
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, myMenu) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(myMenu, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, myMenu);
        if (tmp.children && tmp.children.length > 0) {
          res.push(tmp);
        }
      } else {
        res.push(tmp);
      }
    }
  });
  
  return res;
}

// 将树级数据平铺为list
function handlePermissionData(array,result) {
  for (let index = 0; index < array.length; index++) {
    const element = array[index];

    if (element.code.includes("_btn")) {// 按钮权限
      btnAuthorityList.push(element)
    } else { // 界面权限
      result.push(element)
    }

    if (element.children && element.children.length > 0) {
      handlePermissionData(element.children, result)
    }
  }
}

function getTargetRoute(tempRoutes, permissionData) {
  let permissionMenu = []
  handlePermissionData(permissionData, permissionMenu)

  handleChild(tempRoutes, permissionMenu)
  
  handlePermissionState(tempRoutes)
  return tempRoutes
}


function handlePermissionState(tempRoutes) {
  for (let index = tempRoutes.length - 1; index >= 0; index --) {
    const element = tempRoutes[index];
    if (element.meta) {
      if (element.meta.permission == 0) {
        tempRoutes.splice(index, 1)
      }
      if (element.children && element.children.length > 0) {
        handlePermissionState(element.children)
      }
    }
  }
}

function handleChild(tempRoutes, permissionMenu) {
  for (let index = 0; index < tempRoutes.length; index++) {
    const element = tempRoutes[index];
    if (element.meta) {
      if (element.hidden && element.hidden === true) {
        element.meta.permission = 1
      } else {
        if (element.meta.code) {
          let result = false
          
          // 循环遍历权限菜单匹配
          for (let j = 0; j < permissionMenu.length; j++) {
            const role = permissionMenu[j];
            if (element.meta.code === role.code) {
              result = true
              if (element.meta.code != 'zcyx_info') {
                element.meta.title = role.name
              }
              break
            }
          }

          if (result) {
            element.meta.permission = 1
          } else {
            element.meta.permission = 0
          }
          if (element.children && element.children.length > 0) {
            handleChild(element.children, permissionMenu)
          }
        } else {
          element.meta.permission = 0
        }
      }
    } else {
      element.meta.permission = 0
    }
  }
}

const state = {
  routes: [],
  addRoutes: [],
  myMenu: []
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
  SET_BTN_AUTHORITY: (state, routes) => {
    state.btnAuthority = routes;
  }
};

const actions = {
  generateRoutes({ commit, state }, roles) {
    return new Promise(resolve => {
      getPermissionMenu()
        .then(res => {
          state.myMenu = res || [];
          let accessedRoutes;

          btnAuthorityList = []
          if (!state.myMenu || state.myMenu.length < 1) {
            accessedRoutes = [];
          } else {
            let tempRoutes = Object.assign([], asyncRoutes)
            accessedRoutes = getTargetRoute(tempRoutes,res)
            // accessedRoutes = filterAsyncRoutes(asyncRoutes, state.myMenu);
            console.log('路由数据：',accessedRoutes);
            console.log('按钮数据：',btnAuthorityList);
          }
          accessedRoutes = accessedRoutes.concat({
            path: "*",
            redirect: "/404",
            hidden: true
          });
          
          commit("SET_ROUTES", accessedRoutes);
          commit("SET_BTN_AUTHORITY", btnAuthorityList)
          resolve(accessedRoutes);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
